package com.ddm.service.impl.webImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.constant.MessageConstant;
import com.ddm.dto.page.PageQueryDTO;
import com.ddm.dto.webDTO.cxClassroomDto;
import com.ddm.entity.webEntity.cxClassroom;
import com.ddm.exception.DataErrorException;
import com.ddm.mapper.cxClassroomMapper;
import com.ddm.result.PageResult;
import com.ddm.service.webService.cxClassroomService;
import com.ddm.utils.BeanCopyUtil;
import com.ddm.vo.webVo.cxClassroomVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.tools.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *沉香课堂 服务实现类
 * </p>
 *
 * @author lwj
 * @since 2025-05-7
 */
@Slf4j
@Service
public class cxClassroomServiceImpl extends ServiceImpl<cxClassroomMapper, cxClassroom> implements cxClassroomService {
    @Autowired
    cxClassroomService cxService;
    @Autowired
    cxClassroomMapper cxClassroomMapper;

//    /**
//     * 根据DTO中的唯一信息获取ID
//     * @param classroomDTO 教室信息DTO
//     * @return 记录ID
//     */
//    private Long getIdByUniqueFields(cxClassroomDto classroomDTO) {
//        // 检查必要条件（必须同时有值）
//        if (classroomDTO.getPublisher() == null || classroomDTO.getPublishDate() == null) {
//            throw new IllegalArgumentException("Publisher和PublishDate必须同时提供");
//        }
//
//        LambdaQueryWrapper<cxClassroom> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(cxClassroom::getPublisher, classroomDTO.getPublisher())
//                .eq(cxClassroom::getPublishDate, classroomDTO.getPublishDate());
//
//        cxClassroom classroom = cxService.getOne(wrapper);
//        if (classroom == null) {
//            log.error("获取教室ID失败：未找到匹配记录，Publisher={}, PublishDate={}",
//                    classroomDTO.getPublisher(), classroomDTO.getPublishDate());
//            throw new DataErrorException(MessageConstant.ERROR_DATA);
//        }
//        return classroom.getId();
//    }
    @Override
    public PageResult getCxClassroomList(PageQueryDTO pageQueryDTO) {


        // 分页查询
        Page<cxClassroom> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        LambdaQueryWrapper<cxClassroom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(cxClassroom::getPublishDate);

        // 模糊查询条件：如果关键字不为空，就对 name、content、a 字段做模糊匹配
        String keyword = pageQueryDTO.getKey();
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like(cxClassroom::getName, keyword)
                    .or()
                    .like(cxClassroom::getContent, keyword)
                    .or()
                    .like(cxClassroom::getA, keyword);
        }

        Page<cxClassroom> pageResult = cxService.page(page, queryWrapper);
        List<cxClassroom> records = pageResult.getRecords();
        long total = pageResult.getTotal();

        // 手动转换为VO列表
        List<cxClassroomVo> voList = new ArrayList<>();
        if (records != null && !records.isEmpty()) {
            for (cxClassroom record : records) {
                 cxClassroomVo vo= BeanCopyUtil.BeanCopy(record, cxClassroomVo.class);

                voList.add(vo);
            }
        }

        return new PageResult(total, voList);
    }


    /**
    //     * 更新教室信息
//     * @param classroomDTO 教室信息DTO
//     * @return 更新结果
//     */
    /**
     * 更新教室信息
     *
     * @param classroomDTO 教室信息DTO
     * @return 更新结果
     */
    @Override
    public boolean updateClassroom( cxClassroomDto classroomDTO) {
        long id=classroomDTO.getId();
        // 检查记录是否存在
        cxClassroom existClassroom = getById(id);
        if (existClassroom == null) {
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }

        // 将DTO转换为实体类
        cxClassroom classroom = BeanCopyUtil.BeanCopy(classroomDTO, cxClassroom.class);
        // 设置ID
        classroom.setId(id);

        // 执行更新操作
        updateById(classroom);
        return true;
    }
    // 批量删除课堂（传入ID列表）
    @Override
    public void deleteClassroomList(List<cxClassroomDto> cxClassroomDTOS) {
        // 提取课堂ID列表
        List<Long> classroomIds = cxClassroomDTOS.stream()
                .map(cxClassroomDto::getUserId)
                .collect(Collectors.toList());

        // 批量查询验证课堂存在性
        List<cxClassroom> classrooms = cxClassroomMapper.selectBatchIds(classroomIds);

        // 验证所有课堂都存在
        if (classrooms.size() != classroomIds.size()) {
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }

        // 批量删除课堂（传入ID列表）
        cxClassroomMapper.deleteBatchIds(classroomIds);


    }
    /**
     * 根据DTO中的唯一信息删除教室
     * @param id
     * @return 删除结果
     */
    @Override
    public boolean deleteClassroom(long id) {
        // 检查记录是否存在
        cxClassroom existClassroom = getById(id);
        if (existClassroom == null) {
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }

         removeById(existClassroom);
         return true;
    }
    /**
     * 添加教室信息
     * @param classroomDTO 教室信息DTO
     * @return 添加结果
     */
    @Override
    public boolean addClassroom(cxClassroomDto classroomDTO) {
        if (classroomDTO.getName() == null || classroomDTO.getName().trim().isEmpty()) {

            throw new IllegalArgumentException("课堂名不能为空");

        }
        // 将DTO转换为实体类
        cxClassroom classroom = BeanCopyUtil.BeanCopy(classroomDTO, cxClassroom.class);

        // 设置默认值（如果没有）
        // 设置默认发布时间（如果DTO中未包含）
        if (classroom.getPublishDate() == null) {
            classroom.setPublishDate(LocalDateTime.now());
        }

        // 执行插入操作
         save(classroom);
        return true;
    }

}
